﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DO.DreamOnTrader.Indicator;
using DO.DreamOnTrader.Quote;

namespace DO.DreamOnTrader.Expression
{
	public enum CompareSet { GreaterThan = 0, GreaterThanEqual, Equal, LessThan, LessEqual, GoldenCross, DeathCross }

	/// <summary>
	/// 單一條件式類別，用來判斷指標條件是否成立
	/// </summary>
	public class Expression
	{
		private IIndicator left_Indicator;
		private IIndicator right_Indicator;
		private CompareSet compare;
		private int? gt = null;	//判斷交叉(紀錄前一個比較為大於or小於)
		private bool lastResult = false;

		public Expression(IIndicator _left,CompareSet _compare, IIndicator _right)
		{
			left_Indicator = _left;
			right_Indicator = _right;
			compare = _compare;
		}


		/// <summary>
		/// 比較左值及右值是否達到比較條件
		/// </summary>
		/// <param name="left_value"></param>
		/// <param name="_compare"></param>
		/// <param name="right_value"></param>
		/// <returns></returns>
		protected virtual bool isTrue(float left_value, CompareSet _compare, float right_value)
		{
			bool rs = false;

			if (!float.IsNaN(left_value) && !float.IsNaN(right_value))
			{
				int _gt = left_value.CompareTo(right_value);

				switch (_compare)
				{
					case CompareSet.GreaterThan:
						rs = (_gt > 0);
						break;
					case CompareSet.GreaterThanEqual:
						rs = (_gt >= 0);
						break;
					case CompareSet.Equal:
						rs = (_gt == 0);
						break;
					case CompareSet.LessThan:
						rs = (_gt < 0);
						break;
					case CompareSet.LessEqual:
						rs = (_gt <= 0);
						break;
					case CompareSet.GoldenCross:
						rs = (_gt > 0 && gt <= 0);
						break;
					case CompareSet.DeathCross:
						rs = (_gt < 0 && gt >= 0);
						break;
				}

				gt = _gt;
			}
			return rs;
		}

		/// <summary>
		/// 回傳此條件式是否成立
		/// </summary>
		/// <param name="tick"></param>
		/// <returns></returns>
		public bool isTrue(Tick tick)
		{
			lastResult = isTrue(left_Indicator.getValue(tick), compare, right_Indicator.getValue(tick));
			return lastResult;
		}

		/// <summary>
		/// 回傳此條件式是否成立
		/// </summary>
		/// <param name="kbar"></param>
		/// <returns></returns>
		public bool isTrue(KBar kbar)
		{
			lastResult = isTrue(left_Indicator.getValue(kbar), compare, right_Indicator.getValue(kbar));
			return lastResult;
		}

		/// <summary>
		/// 回傳識別標籤
		/// </summary>
		/// <returns></returns>
		public virtual string Label()
		{
			return left_Indicator.Label() + " " + compare + " " + right_Indicator.Label();
		}

		/// <summary>
		/// 回傳指標的識別標籤及值
		/// </summary>
		/// <returns></returns>
		public override string ToString()
		{
			return left_Indicator.ToString() + " " + compare + " " + right_Indicator.ToString() + ":" + lastResult;
		}
	}
}
